﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hallenberg.SmartClient.Interfaces;
using System.Diagnostics;
using System.Threading;
using Hallenberg.SmartClient.Properties;

namespace Hallenberg.SmartClient.TypeHandlers
{
    public abstract class BaseClassTypeHandler<TInterface, TMustInheritFrom> : IClassTypeHandler
        where TMustInheritFrom : TInterface
    {
        private IServiceLocator m_ServiceLocator;

        protected BaseClassTypeHandler(IServiceLocator serviceLocator)
        {
            m_ServiceLocator = serviceLocator;
        }

        public Type HandledBaseType
        {
            get
            {
                return typeof(TMustInheritFrom);
            }
        }

        public bool CanHandle(Type type)
        {
            return type.IsSubclassOf(typeof(TMustInheritFrom));
        }

        public bool Handle(Type type)
        {
            Debug.Assert(type != null);
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (type == typeof(TMustInheritFrom))
            {
                return false;
            }

            Debug.Assert(type.IsSubclassOf(typeof(TMustInheritFrom)));
            if (!type.IsSubclassOf(typeof(TMustInheritFrom)))
            {
                throw new ArgumentException(string.Format(Thread.CurrentThread.CurrentCulture, Resources.ArgumentException_NotCorrectlyDerivedType, type.Name), "type");
            }

            m_ServiceLocator.RegisterType(typeof(TInterface), type, type.Name);

            return true;
        }
    }
}
